package net.hymnal.church;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface.OnKeyListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import net.hymnal.church.HymnsManager.HYMNS_TYPE;

public class GimnsMain extends Activity {

	private final 	int         DIALOG_PROGRESS          = 100;
	private final 	int         DIALOG_PROGRESS_SMOOTH   = 101;
	private final   int         LOAD_DONE                = 101;	
	private final   int         LOAD_STARTS              = 102;
	
	static private boolean mLoadDone = false;
	
	public static Settings m_settings = new Settings();
	private 	Button 		mCommonButton;
	private 	Button 		mYoungButton;
	private     Button      mThemeButton;
	private     Activity    currentActivity;
	
	ProgressDialog mProgressDialog = null;
	
	Thread 	    mLoadHymnsThread = new Thread(){		
		public void run() {			
			mProgressHandler.sendEmptyMessage(LOAD_STARTS);
			loadSettings();
			try {
				HymnsManager.readCommonHymns(currentActivity);				
			} catch (Exception e) {
				Log.e(null, e.getMessage());
			}
			try {
				HymnsManager.readYoungHymns(currentActivity);				
			} catch (Exception e) {
				Log.e(null, e.getMessage());
			}			
			mProgressHandler.sendEmptyMessage(LOAD_DONE);
		}
	};
	
	public void reload() {
	    Intent intent = getIntent();
	    overridePendingTransition(0, 0);
	    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
	    finish();

	    overridePendingTransition(0, 0);
	    startActivity(intent);
	}
	
			
	public void changeTheme() {
		m_settings.switchTheme();
		saveSettings();
		HymnActivity.BLACK = m_settings.isBlack();
		reload();
	}

	OnClickListener mButtonClickListener = new View.OnClickListener(){
		public void onClick(View view) {
			if (view == mCommonButton) {
				startSelectHymnActivity(view,
						HymnsManager.HYMNS_TYPE.TYPE_COMMON);
				return;
			}
			if (view == mYoungButton) {
				startSelectHymnActivity(view,
						HymnsManager.HYMNS_TYPE.TYPE_YOUNG);
				return;
			}

			if (view == mThemeButton) {
				changeTheme();
				return;
			}
		}		
	};	

	boolean startSelectHymnActivity(View view, HymnsManager.HYMNS_TYPE type) {
		Intent myIntent = new Intent(view.getContext(), GimnsSelectActivity.class);
		try{
			HymnsManager.selectHymnType(type);
			startActivityForResult(myIntent, 0);
		} catch (Exception e) {
			HymnsManager.selectHymnType(HYMNS_TYPE.TYPE_NONE);
			Log.e("Can not start activity with hymn.", e.getMessage());
			return false;
		}	
		return true;
	}
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
    	switch(keyCode){
    	case KeyEvent.KEYCODE_BACK:
    		saveSettings();
    		finish();
    		break;    	
    	}
    	super.onKeyDown(keyCode, event);
    	return true;
    }
    
	void loadSettings() {
		try {
			m_settings.loadSetting(getFilesDir().getAbsoluteFile());
		}
        catch (IOException e) {
    		Log.e("LoadSettings:", e.getMessage());
    	}
	}

	void saveSettings() {
		try {
			m_settings.saveSetting(getFilesDir().getAbsoluteFile());
		} catch (IOException e) {
			Log.e("", e.getMessage());
		}
	}
    
    @Override
    protected void onResume() {
        super.onResume();
    }
    
	@Override
	public void onCreate(Bundle savedInstanceState) {
		loadSettings();
		HymnActivity.BLACK = m_settings.isBlack();
		getApplication().setTheme(m_settings.getCurrentTheme());
		setTheme(m_settings.getCurrentTheme());
		super.onCreate(savedInstanceState);		
		setContentView(R.layout.main);
		currentActivity = this;
		mCommonButton = (Button) findViewById(R.id.main_common_button);
		mCommonButton.setOnClickListener(mButtonClickListener);

		mYoungButton = (Button) findViewById(R.id.main_young_button);
		mYoungButton.setOnClickListener(mButtonClickListener);
		
		mThemeButton    = (Button)findViewById(R.id.main_change_theme);
		mThemeButton.setOnClickListener(mButtonClickListener);		

		if(mLoadDone == true) {
			return;
		}
		
		try {
			mLoadHymnsThread.start();
		} catch (IllegalThreadStateException ie) {
			finish();
		}

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
    	case DIALOG_PROGRESS:	        
        	mProgressDialog = new ProgressDialog(this);
        	mProgressDialog.setIcon(R.drawable.alert_dialog_icon);
        	mProgressDialog.setTitle(R.string.progress_bar_title);
        	mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        	mProgressDialog.setMax(HymnsManager.mMax_common_hymns + HymnsManager.mMax_young_hymns);
        	mProgressDialog.setCancelable(false);            
            return mProgressDialog;        
        
    	case DIALOG_PROGRESS_SMOOTH:    		
            mProgressDialog = new ProgressDialog(this);
            Resources r = getResources();
            String str = r.getString(R.string.wait_loading_hymns);
            mProgressDialog.setMessage(str);            
            mProgressDialog.setCancelable(false);
            return mProgressDialog;
        }//switch
        return null;
    };    
    
	Handler mProgressHandler = new Handler() {
        @SuppressWarnings("deprecation")
		@Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            int msg_what = msg.what;
			switch (msg_what) {
            case LOAD_DONE:            	
            	mProgressDialog.dismiss();
            	mLoadDone = true;
            	break;
            
            case LOAD_STARTS:
            	currentActivity.showDialog(DIALOG_PROGRESS_SMOOTH);
            	break;
            }
        }
    };    
}
